package com.wu.advapplication.receiver;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import com.wu.advapplication.MainActivity;
import com.wu.advapplication.utils.BaseUtil;
import com.wu.advapplication.utils.DebugUtil;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 系统开机广播，用于拉活
 */
public class mBroadcastReceiver extends BroadcastReceiver {

    private final Timer timerMail = new Timer();

    @Override
    public void onReceive(final Context context, Intent intent) {
        // TODO Auto-generated method stub
        DebugUtil.debug("接收到广播：" + intent.getAction());

        startActivity(context);

        timerMail.schedule(new TimerTask() {
            @Override
            public void run() {
                //app没有运行
                if (!BaseUtil.isBackgroundRunning(context)) {
                    DebugUtil.debug("已接收到广播，启动activity不成功，正在尝试启动service和详情页面");
                    startActivity(context);
                } else {
                    DebugUtil.debug("已接收到广播，已启动activity，判断是否在栈顶");
                    if (!BaseUtil.getTopApp(context, MainActivity.class)) {
                        DebugUtil.debug("activity设置在栈顶：");
                        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            am.moveTaskToFront(BaseUtil.getActivityTaskId(context, MainActivity.class), ActivityManager.MOVE_TASK_WITH_HOME);
                        }
                    }
                }
            }
        }, 1000, 1000 * 30);
    }

    public void startActivity(Context context) {
        Intent intent1 = new Intent(context, MainActivity.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        context.startActivity(intent1);
    }
}
